package com.mzw.huaxiarealestatebackend.common.utils;

import java.text.DecimalFormat;

public class FileUtil {
    public static String formatFileSize(long sizeInBytes) {
        if (sizeInBytes <= 0) {
            return "0 B";
        }

        final String[] units = {"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(sizeInBytes) / Math.log10(1024));

        return new DecimalFormat("#,##0.#").format(sizeInBytes / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

    public static long parseFileSize(String fileSizeString) {
        if (fileSizeString == null || fileSizeString.isEmpty()) {
            return 0L;
        }

        String[] parts = fileSizeString.split(" ");
        if (parts.length != 2) {
            throw new IllegalArgumentException("Invalid file size format: " + fileSizeString);
        }

        double sizeValue;
        try {
            sizeValue = Double.parseDouble(parts[0]);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Invalid file size value: " + parts[0]);
        }

        String unit = parts[1].toUpperCase();
        switch (unit) {
            case "B":
                return (long) sizeValue;
            case "KB":
                return (long) (sizeValue * 1024);
            case "MB":
                return (long) (sizeValue * 1024 * 1024);
            case "GB":
                return (long) (sizeValue * 1024 * 1024 * 1024);
            case "TB":
                return (long) (sizeValue * 1024 * 1024 * 1024 * 1024);
            default:
                throw new IllegalArgumentException("Unsupported file size unit: " + unit);
        }
    }
}
